import type { ProColumns } from "@ant-design/pro-components";
import { EditableProTable } from "@ant-design/pro-components";
import { Tooltip } from "antd";
import React, { useState } from "react";

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

type DataSourceType = {
  id: React.Key;
  title?: string;
  readonly?: string;
  decs?: string;
  state?: string;
  created_at?: number;
  update_at?: number;
  children?: DataSourceType[];
};

const defaultData: DataSourceType[] = [
  {
    id: 624748504,
    incentiveSubject: "半年度奖励",
    incentiveAmount: 12009,
    subCategory: "text1",
    evaluationWeight: 90,
    remark: "好的伤口恢复gdjskgfdskj过分解读个富可敌国分开的",
    created_at: 1590486176000,
    update_at: 1590486176000,
  },
];

const EditTableProPage = () => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<readonly DataSourceType[]>([]);
  const [position, setPosition] = useState<"top" | "bottom" | "hidden">(
    "bottom"
  );

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: "激励科目",
      dataIndex: "incentiveSubject",
      valueType: "select",
      tooltip: "只读，使用form.getFieldValue获取不到值",
      valueEnum: { text: "半年度奖惩" },
      formItemProps: (form, { rowIndex }) => {
        return {
          rules:
            rowIndex > 1 ? [{ required: true, message: "此项为必填项" }] : [],
        };
      },
    },
    {
      title: "激励奖金(元)",
      dataIndex: "incentiveAmount",
      valueType: "money",
      tooltip: "只读，使用form.getFieldValue可以获取到值",
      // readonly: true,
      // width: '15%',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules:
            rowIndex > 1 ? [{ required: true, message: "此项为必填项" }] : [],
        };
      },
    },
    {
      title: "激励科目小类",
      key: "subCategory",
      dataIndex: "subCategory",
      valueType: "select",
      valueEnum: {
        text1: "客户满意度",
        text2: "中台专业品控",
        text3: "AG走楼体验",
      },
      formItemProps: (form, { rowIndex }) => {
        return {
          rules:
            rowIndex > 1 ? [{ required: true, message: "此项为必填项" }] : [],
        };
      },
    },
    {
      title: "考评权重",
      dataIndex: "evaluationWeight",
      valueType: "percent",
      formItemProps: (form, { rowIndex }) => {
        return {
          rules:
            rowIndex > 1 ? [{ required: true, message: "此项为必填项" }] : [],
        };
      },
    },
    {
      title: "考评金额（元）",
      dataIndex: "evaluationWeight11",
      // editable:false,
      fieldProps: (form, { rowKey, rowIndex }) => {
        return {
          disabled: true,
        };
      },
      formItemProps: (form, { rowIndex }) => {
        return {
          rules:
            rowIndex > 1 ? [{ required: true, message: "此项为必填项" }] : [],
        };
      },
      render: (v, r) => {
        return (r.incentiveAmount * (r.evaluationWeight / 100)).toFixed(2);
      },
    },
    {
      title: "备注",
      dataIndex: "remark",
      ellipsis: true,
      render: (v, r) => {
        return (
          <Tooltip title={v}>
            <span>{v}</span>
          </Tooltip>
        );
      },

      formItemProps: (form, { rowIndex }) => {
        return {
          rules:
            rowIndex > 1 ? [{ required: true, message: "此项为必填项" }] : [],
        };
      },
    },
    {
      title: "操作",
      valueType: "option",
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
        >
          编辑
        </a >,
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.id !== record.id));
          }}
        >
          删除
        </a >,
      ],
    },
  ];
  const handleChange = (value) => {
    console.log(value, "value");
    setDataSource(value);
  };
  return (
    <>
      <EditableProTable<DataSourceType>
        rowKey="id"
        headerTitle="可编辑表格"
        maxLength={5}
        scroll={{
          x: 960,
        }}
        recordCreatorProps={
          position !== "hidden"
            ? {
                position: position as "top",
                record: () => ({ id: (Math.random() * 1000000).toFixed(0) }),
              }
            : false
        }
        loading={false}
        columns={columns}
        request={async () => ({
          data: defaultData,
          total: 3,
          success: true,
        })}
        value={dataSource}
        onChange={handleChange}
        editable={{
          type: "multiple",
          editableKeys,
          onSave: async (rowKey, data, row) => {
            console.log(rowKey, data, row);
            await waitTime(1000);
          },
          onChange: setEditableRowKeys,
        }}
      />
    </>
  );
};

export default EditTableProPage;